package pers.vic.base.bo.system;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;


/**
 * 存放用户信息的对象
 *  可能包括用户基本信息  登录信息 菜单( 按钮)息等
 * @author VIC
 *
 */
public class Principal implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * menu tree
	 */
	private List<SysMenu> menus;

	/**
	 * login user
	 */
	private SysUser user;
	
	/**
	 * menu Map--> 但是包含父子结构 URL-->menu
	 */
	private Map<String, SysMenu> menuIndex = new HashMap<String, SysMenu>();
	
	/**当前位置用于页面展示*/
	private Set<SysMenu> position = new TreeSet<SysMenu>();
	
	/**
	 * current URL
	 */
	private String location;
	
	
	
	public Principal(){}
	
	public Principal(SysUser user) {
		this.user = user;
	}
	
	public int getUserId(){
		return user != null ? user.getId() : 0;
	}
	
	public String getNickname(){
		return user != null ? user.getNickname() : "";
	}
	public String getUsername(){
		return user != null ? user.getUsername() : "";
	}
	
	
	public Principal(SysUser user, List<SysMenu> menus) {
		this.user = user;
		this.menus = menus;
		locationIndex(menus);
	}

	/**把树形菜单还原成map*/
	private void locationIndex(List<SysMenu> menus) {
		if(menus == null) {
			return;
		}
		for(SysMenu m :menus) {
			menuIndex.put(m.getUrl(), m);
			List<SysMenu> subMenus = m.getChildren();
			if(subMenus !=null) {
				locationIndex(subMenus);
			}
		}
	}
	/**
	 * 设置此URL在菜单中的位置(找到它的父菜单-->父菜单...)
	 */
	public void setPosition(String url) {
		position.clear();
		SysMenu menu = menuIndex.get(url);
		if(menu != null) {
			addMenuToPosition(menu);
		}
	}
	
	private void addMenuToPosition(SysMenu menu){
		position.add(menu);
		if(menu.getParent() != null) {
			addMenuToPosition(menu.getParent());
		}
	}

	
	/************************* get and set ↓↓ ↓↓ ↓↓ ***************************************************************/
	
	public List<SysMenu> getMenus() {
		return menus;
	}

	public void setMenus(List<SysMenu> menus) {
		this.menus = menus;
	}

	public SysUser getUser() {
		return user;
	}

	public void setUser(SysUser user) {
		this.user = user;
	}

	public Set<SysMenu> getPosition() {
		return position;
	}

	public void setPosition(Set<SysMenu> position) {
		this.position = position;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}
	
	
	
}
